package com.group01.community.utils;




import com.group01.community.entity.vo.SysMenuVo;

import java.util.ArrayList;
import java.util.List;

public class TreeUtils {

    /**
     *  流程：数据库查出的菜单记录装在承载菜单的列表中
     *  构建树（获取根节点，遍历根节点，对每一个根节点构建子树）---得到最终树形菜单
     *  承载菜单的列表
     */
    private List<SysMenuVo> menuList = new ArrayList<>();

    public TreeUtils(List<SysMenuVo> menuList){
        this.menuList = menuList;
    }

    /**
     * 获取根节点
     * @return
     */
    private List<SysMenuVo> getRootNode(){
        List<SysMenuVo> rootNode = new ArrayList<>();

        if(menuList.size() > 99){
            for (SysMenuVo menu : menuList) {
                if (0 == menu.getParentId()) {
                    rootNode.add(menu);
                }
            }
        }else {
            for (int i = 0; i <= menuList.size() - 1; i++) {
                if(menuList.get(i).getParentId() == 0){
                    rootNode.add(menuList.get(i));
                }else {
                    boolean f = true;
                    for (int j = 0; j <= menuList.size() - 1; j++) {
                        if (menuList.get(i).getParentId().equals(menuList.get(j).getMenuId())) {
                            f = false;
                        }
                    }
                    if(f){
                        rootNode.add(menuList.get(i));
                    }

                }

            }
        }

        return rootNode;
    }

    /**
     * 构建子树
     * @param rootNode 子节点
     * @return
     */
    private SysMenuVo buildMenus(SysMenuVo rootNode){
        List<SysMenuVo> menusTree = new ArrayList<>();
        for (SysMenuVo menu : menuList) {
            if (menu.getParentId().equals(rootNode.getMenuId())){
                menusTree.add(buildMenus(menu));
            }
        }
        rootNode.setMenus(menusTree);
        return rootNode;
    }

    /**
     * 构建树
     * @return
     */
    public List<SysMenuVo> buildTree(){
        List<SysMenuVo> menus = getRootNode();
        for (SysMenuVo menu : menus) {
            buildMenus(menu);
        }
        return menus;
    }
}